<?php

error_reporting(7);
set_magic_quotes_runtime(0);

$old_error_handler = set_error_handler("myErrorHandler");

define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());

$_DCACHE = array();

define('HTKOU_ROOT', substr(dirname(__FILE__),0,-3));
define('UC_CLIENT_ROOT', HTKOU_ROOT.'/uc_client');

require_once UC_CLIENT_ROOT.'/config.inc.php';
require_once HTKOU_ROOT.'/config/db_settings.php';

$code = $_GET['code'];
parse_str(authcode($code, 'DECODE', UC_KEY), $get);
if(MAGIC_QUOTES_GPC) {
	$get = dstripslashes($get);
}

if(time() - $get['time'] > 3600) {
	exit('Authracation has expiried');
}
if(empty($get)) {
	exit('Invalid Request');
}
$action = $get['action'];
$timestamp = time();

global $db_settings, $connid;
$connid = connect_db($db_settings['host'], $db_settings['user'], $db_settings['password'], $db_settings['database'],$db_settings['client_charset']);
get_settings();

if($action == 'test') {
	error_log("test", 3, "C:/poc/log/HTKou.log");
	
	exit(API_RETURN_SUCCEED);

} elseif($action == 'deleteuser') {

	!API_DELETEUSER && exit(API_RETURN_FORBIDDEN);
	exit(API_RETURN_SUCCEED);

} elseif($action == 'renameuser') {

	!API_RENAMEUSER && exit(API_RETURN_FORBIDDEN);
	exit(API_RETURN_SUCCEED);

} elseif($action == 'gettag') {

	!API_GETTAG && exit(API_RETURN_FORBIDDEN);
	exit(API_RETURN_SUCCEED);
	
} elseif($action == 'synlogin') {
	error_log("synlogin \n", 3, "C:/poc/log/HTKou.log");
	
	!API_SYNLOGIN && exit(API_RETURN_FORBIDDEN);

	$uid = intval($get['uid']);	
	$uc_username = $get['username'];	
	$uc_password = $get['password'];	
	error_log("uid ".$uid."\n", 3, "C:/poc/log/HTKou.log");
	error_log("username ".$uc_username."\n", 3, "C:/poc/log/HTKou.log");
	error_log("password ".$uc_password."\n", 3, "C:/poc/log/HTKou.log");
	
	// use username
	$result = mysql_query("SELECT user_id, user_name, user_real_name, user_pw, user_type, UNIX_TIMESTAMP(last_login) AS last_login, UNIX_TIMESTAMP(last_logout) AS last_logout, thread_order, user_view, sidebar, fold_threads, thread_display, time_difference, activate_code FROM ".$db_settings['userdata_table']." WHERE lower(user_name) = '".mysql_real_escape_string(strtolower($uc_username))."'", $connid) or raise_error('database_error',mysql_error());
	
	// use uid
	//$result = mysql_query("SELECT user_id, user_name, user_real_name, user_pw, user_type, UNIX_TIMESTAMP(last_login) AS last_login, UNIX_TIMESTAMP(last_logout) AS last_logout, thread_order, user_view, sidebar, fold_threads, thread_display, time_difference, activate_code FROM ".$db_settings['userdata_table']." WHERE user_id = ".$uid, $connid) or raise_error('database_error',mysql_error());
    if (mysql_num_rows($result) == 1) { 	
       $feld = mysql_fetch_array($result);
	   error_log("user found ".$feld['user_name']."\n", 3, "C:/poc/log/HTKou.log");	   
	   
	   /* TBD validate password
	    * 
       if($feld["user_pw"] == md5($request_userpw)) {
			exit(API_RETURN_FAILED);
       }
	   */
	   
       if(trim($feld["activate_code"]) != '') {
			exit(API_RETURN_FAILED);
       }
       $user_id = $feld["user_id"];
       $user_name = $feld["user_name"];
       $user_type = $feld["user_type"];
              
       header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
              
       if(isset($settings['autologin']) && $settings['autologin'] == 1) {
	       error_log("auto login\n", 3, "C:/poc/log/HTKou.log");
       	   $cookie_auto_login_code = md5(uniqid(rand()));
           $auto_login_code = md5($cookie_auto_login_code);
           setcookie($settings['session_prefix'].'auto_login',$feld['user_id'].'.'.$cookie_auto_login_code,time()+(3600*24*30), "/");
       } else {
       	   exit(API_RETURN_FAILED);
       } 
	          
	   @mysql_query("UPDATE ".$db_settings['userdata_table']." SET logins=logins+1, last_login=NOW(), last_logout=NOW(), registered=registered, auto_login_code='".mysql_real_escape_string($auto_login_code)."' WHERE user_id='".$user_id."'", $connid);
       //if($user_type>0 && $settings['auto_delete_spam']>0) @mysql_query("DELETE FROM ".$db_settings['forum_table']." WHERE time < (NOW() - INTERVAL ".$settings['auto_delete_spam']." HOUR) AND spam=1", $connid);       
       if ($db_settings['useronline_table'] != "") {
           @mysql_query("DELETE FROM ".$db_settings['useronline_table']." WHERE ip = '".$_SERVER['REMOTE_ADDR']."'", $connid);
       }

	   error_log("success \n", 3, "C:/poc/log/HTKou.log");	   
       //exit(API_RETURN_SUCCEED);
     } else { 
     	error_log("user not found", 3, "C:/poc/log/HTKou.log");
        if($settings['temp_block_ip_after_repeated_failed_logins']==1) count_failed_logins();
       	exit(API_RETURN_FAILED);
     } 
} elseif($action == 'synlogout') {

	!API_SYNLOGOUT && exit(API_RETURN_FORBIDDEN);
    session_start();
	$uid = intval($_SESSION[$settings['session_prefix'].'user_id']);
	error_log("logout ".$uid."\n", 3, "C:/poc/log/HTKou.log");
	header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
    session_destroy();
	setcookie($settings['session_prefix'].'auto_login','',0, '/');
  	if($db_settings['useronline_table'] != '') @mysql_query("DELETE FROM ".$db_settings['useronline_table']." WHERE ip = 'uid_".$uid."'", $connid);
	
} elseif($action == 'updatepw') {

	!API_UPDATEPW && exit(API_RETURN_FORBIDDEN);
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updatebadwords') {

	!API_UPDATEBADWORDS && exit(API_RETURN_FORBIDDEN);

	$post = uc_unserialize(file_get_contents('php://input'));
	$cachefile = HTKOU_ROOT.'./uc_client/data/cache/badwords.php';
	$fp = fopen($cachefile, 'w');
	$s = "<?php\r\n";
	$s .= '$_CACHE[\'badwords\'] = '.var_export($post, TRUE).";\r\n";
	fwrite($fp, $s);
	fclose($fp);
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updatehosts') {

	!API_UPDATEHOSTS && exit(API_RETURN_FORBIDDEN);

	$post = uc_unserialize(file_get_contents('php://input'));
	$cachefile = HTKOU_ROOT.'./uc_client/data/cache/hosts.php';
	$fp = fopen($cachefile, 'w');
	$s = "<?php\r\n";
	$s .= '$_CACHE[\'hosts\'] = '.var_export($post, TRUE).";\r\n";
	fwrite($fp, $s);
	fclose($fp);
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updateapps') {

	!API_UPDATEAPPS && exit(API_RETURN_FORBIDDEN);

	$post = uc_unserialize(file_get_contents('php://input'));
	$UC_API = $post['UC_API'];
	unset($post['UC_API']);

	$cachefile = HTKOU_ROOT.'./uc_client/data/cache/apps.php';
	$fp = fopen($cachefile, 'w');
	$s = "<?php\r\n";
	$s .= '$_CACHE[\'apps\'] = '.var_export($post, TRUE).";\r\n";
	fwrite($fp, $s);
	fclose($fp);

	if(is_writeable(UC_CLIENT_ROOT.'./config.inc.php')) {
		$configfile = trim(file_get_contents(UC_CLIENT_ROOT.'./config.inc.php'));
		$configfile = substr($configfile, -2) == '?>' ? substr($configfile, 0, -2) : $configfile;
		$configfile = preg_replace("/define\('UC_API',\s*'.*?'\);/i", "define('UC_API', '$UC_API');", $configfile);
		if($fp = @fopen(UC_CLIENT_ROOT.'./config.inc.php', 'w')) {
			@fwrite($fp, trim($configfile));
			@fclose($fp);
		}
	}

	exit(API_RETURN_SUCCEED);

} elseif($action == 'updateclient') {

	!API_UPDATECLIENT && exit(API_RETURN_FORBIDDEN);

	$post = uc_unserialize(file_get_contents('php://input'));
	$cachefile = HTKOU_ROOT.'./uc_client/data/cache/settings.php';
	$fp = fopen($cachefile, 'w');
	$s = "<?php\r\n";
	$s .= '$_CACHE[\'settings\'] = '.var_export($post, TRUE).";\r\n";
	fwrite($fp, $s);
	fclose($fp);
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updatecredit') {

	!UPDATECREDIT && exit(API_RETURN_FORBIDDEN);
	exit(API_RETURN_SUCCEED);

} elseif($action == 'getcreditsettings') {

	!API_GETCREDITSETTINGS && exit(API_RETURN_FORBIDDEN);

} elseif($action == 'updatecreditsettings') {

	!API_UPDATECREDITSETTINGS && exit(API_RETURN_FORBIDDEN);
	exit(API_RETURN_SUCCEED);

} else {
	exit(API_RETURN_FAILED);

}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	$ckey_length = 4;

	$key = md5($key ? $key : UC_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}

function dsetcookie($var, $value, $life = 0, $prefix = 1) {
	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	setcookie(($prefix ? $cookiepre : '').$var, $value,
		$life ? $timestamp + $life : 0, $cookiepath,
		$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}

function dstripslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

function uc_serialize($arr, $htmlon = 0) {
	include_once UC_CLIENT_ROOT.'./lib/xml.class.php';
	return xml_serialize($arr, $htmlon);
}

function uc_unserialize($s) {
	include_once UC_CLIENT_ROOT.'./lib/xml.class.php';
	return xml_unserialize($s);
}

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
	error_log(date('d/m/y : H:i:s')." error String: ".$errstr.". Error File: ".$errfile.". Error Line: ".$errline."\n",
	 3, "C:/poc/log/HTKou.log");
}

function connect_db($host,$user,$pw,$db)
 {
  global $lang;
  $connid = @mysql_connect($host, $user, $pw) or raise_error('mysql_connect',mysql_error());
  @mysql_select_db($db, $connid) or raise_error('mysql_select_db',mysql_error());
  mysql_query("set names utf8");
  return $connid;
 }

 function get_settings()
 {
  global $lang, $connid, $db_settings, $settings;
  $result = mysql_query("SELECT name, value FROM ".$db_settings['settings_table'], $connid) or raise_error('database_error',mysql_error());
  while ($line = mysql_fetch_array($result))
   {
    $settings[$line['name']] = stripslashes($line['value']);
   }
  mysql_free_result($result);
 }

?>